import logging
import winsound
from PyQt5.QtWidgets import (QMainWindow, QTabWidget, QVBoxLayout, QWidget,
                             QTableWidget, QTableWidgetItem, QHeaderView,
                             QPushButton, QLabel, QSpinBox, QComboBox,
                             QGroupBox, QHBoxLayout, QTextEdit, QFormLayout,
                             QStatusBar, QProgressBar, QAbstractItemView,
                             QDialog, QDialogButtonBox, QDateEdit, QSplitter,
                             QMessageBox, QToolBar, QAction, QDialog, QVBoxLayout,
                             QScrollArea)
from PyQt5.QtCore import Qt, pyqtSlot, QDate, QDateTime, QTimer
from PyQt5.QtGui import QColor, QIcon, QPainter
from datetime import datetime
import threading
import time

logger = logging.getLogger(__name__)


class TradingSystemUI(QMainWindow):
    def __init__(self, system):
        super().__init__()
        self.system = system
        self.sound_enabled = True
        self.popular_stocks_cache = {}  # 缓存热门股票数据

        # 初始化属性
        self.last_monitor_refresh = None
        self.last_simulated_refresh = None
        self.monitor_status_label = None
        self.simulated_status_label = None
        self.monitor_table = None
        self.simulated_table = None
        self.log_text = None
        self.tabs = None
        self.start_button = None
        self.stop_button = None
        self.interval_spin = None
        self.status_label = None
        self.progress_bar = None
        self.popular_stocks_table = None
        self.start_monitoring = self._start_monitoring
        self.stop_monitoring = self._stop_monitoring
        self.init_ui()

        # 连接监控信号
        self.system.monitor.new_trade_found.connect(self.handle_new_trade)
        self.system.monitor.status_update.connect(self.handle_status_update)
        self.system.monitor.log_message.connect(self.handle_log_message)

        # 设置定时器，每5分钟刷新一次热门股票
        self.popular_stocks_timer = QTimer(self)
        self.popular_stocks_timer.timeout.connect(self.refresh_popular_stocks)
        self.popular_stocks_timer.start(5 * 60 * 1000)  # 5分钟

        # 设置每日9:15自动启动监控的定时器
        self.auto_start_timer = QTimer(self)
        self.auto_start_timer.timeout.connect(self.check_auto_start)
        self.auto_start_timer.start(60 * 1000)  # 每分钟检查一次

        logger.info("用户界面初始化完成")

    # 将关键方法放在初始化方法之前
    def init_ui(self):
        """初始化用户界面"""
        # 设置主窗口属性
        self.setWindowTitle('股票跟单系统')
        self.setGeometry(300, 300, 1200, 800)

        # 创建主布局和容器
        main_widget = QWidget()
        main_layout = QVBoxLayout()
        main_widget.setLayout(main_layout)
        self.setCentralWidget(main_widget)

        # 创建选项卡
        self.tabs = QTabWidget()
        main_layout.addWidget(self.tabs)

        # 创建监控选项卡
        self.create_monitor_tab()

        # 创建状态栏
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)

        # 添加状态栏组件
        self.status_label = QLabel("就绪")
        self.status_bar.addWidget(self.status_label)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMaximumWidth(200)
        self.status_bar.addPermanentWidget(self.progress_bar)

    def create_monitor_tab(self):
        """创建监控选项卡"""
        monitor_tab = QWidget()
        layout = QVBoxLayout(monitor_tab)

        # ===================== 系统控制区域 =====================
        control_group = QGroupBox("系统控制")
        control_layout = QHBoxLayout(control_group)

        # 启动按钮
        self.start_button = QPushButton("启动监控")
        self.start_button.setStyleSheet("background-color: #4CAF50; color: white;")
        self.start_button.clicked.connect(self.start_monitoring)  # 修复1: 使用正确的方法引用
        control_layout.addWidget(self.start_button)

        # 停止按钮
        self.stop_button = QPushButton("停止监控")
        self.stop_button.setStyleSheet("background-color: #F44336; color: white;")
        self.stop_button.setEnabled(False)
        self.stop_button.clicked.connect(self.stop_monitoring)  # 修复1: 使用正确的方法引用
        control_layout.addWidget(self.stop_button)

        # 监控间隔设置
        interval_layout = QHBoxLayout()
        interval_layout.addWidget(QLabel("监控间隔(秒):"))

        self.interval_spin = QSpinBox()
        self.interval_spin.setRange(30, 600)  # 60秒到600秒
        self.interval_spin.setValue(100)  # 默认300秒
        interval_layout.addWidget(self.interval_spin)
        control_layout.addLayout(interval_layout)
        logger.debug(f"监控间隔微调框已创建，当前值: {self.interval_spin.value()}")
        # 声音开关
        sound_layout = QHBoxLayout()
        sound_layout.addWidget(QLabel("声音提醒:"))

        self.sound_toggle = QComboBox()
        self.sound_toggle.addItem("开启", True)
        self.sound_toggle.addItem("关闭", False)
        self.sound_toggle.setCurrentIndex(0)
        self.sound_toggle.currentIndexChanged.connect(self.toggle_sound)
        sound_layout.addWidget(self.sound_toggle)
        control_layout.addLayout(sound_layout)

        control_layout.addStretch()
        layout.addWidget(control_group)

        # ===================== 监控记录区域 =====================
        # 创建水平布局容器，用于放置两个表格
        tables_container = QWidget()
        tables_layout = QHBoxLayout(tables_container)

        # 左侧：监控高手记录框
        left_panel = QWidget()
        left_layout = QVBoxLayout(left_panel)

        # 监控高手记录框
        self.monitor_group = QGroupBox("监控高手记录")
        monitor_layout = QVBoxLayout(self.monitor_group)

        # 监控状态标签
        self.monitor_status_layout = QHBoxLayout()
        self.monitor_status_label = QLabel("上次更新: - | 新增: 0条")
        self.monitor_status_label.setStyleSheet("font-weight: bold; color: #333;")
        self.monitor_status_layout.addWidget(self.monitor_status_label)
        self.monitor_status_layout.addStretch()

        # 添加刷新按钮
        self.refresh_monitor_btn = QPushButton("刷新")
        self.refresh_monitor_btn.clicked.connect(self.refresh_monitor_trades)
        self.monitor_status_layout.addWidget(self.refresh_monitor_btn)

        monitor_layout.addLayout(self.monitor_status_layout)

        # 监控高手表格
        self.monitor_table = QTableWidget(0, 8)
        self.monitor_table.setHorizontalHeaderLabels([
            "时间", "高手", "股票代码", "股票名称", "操作", "价格", "数量", "状态"
        ])
        self.monitor_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.monitor_table.setSelectionBehavior(QAbstractItemView.SelectRows)

        # 设置高手名称可点击
        self.monitor_table.cellClicked.connect(self.show_master_trades)

        monitor_layout.addWidget(self.monitor_table)

        left_layout.addWidget(self.monitor_group)

        # 右侧：热门股票统计框
        right_panel = QWidget()
        right_layout = QVBoxLayout(right_panel)

        # 热门股票统计框
        self.popular_stocks_group = QGroupBox("热门股票统计")
        popular_layout = QVBoxLayout(self.popular_stocks_group)

        # 热门股票状态标签
        self.popular_status_layout = QHBoxLayout()
        self.popular_status_label = QLabel("上次更新: - | 热门股票数: 0")
        self.popular_status_label.setStyleSheet("font-weight: bold; color: #333;")
        self.popular_status_layout.addWidget(self.popular_status_label)
        self.popular_status_layout.addStretch()

        # 添加刷新按钮
        self.refresh_popular_btn = QPushButton("刷新")
        self.refresh_popular_btn.clicked.connect(self.refresh_popular_stocks)
        self.popular_status_layout.addWidget(self.refresh_popular_btn)

        popular_layout.addLayout(self.popular_status_layout)

        # 热门股票表格
        self.popular_stocks_table = QTableWidget(0, 3)
        self.popular_stocks_table.setHorizontalHeaderLabels([
            "股票代码", "股票名称", "买入高手数"
        ])
        self.popular_stocks_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 设置点击事件
        self.popular_stocks_table.cellClicked.connect(self.show_master_details)
        popular_layout.addWidget(self.popular_stocks_table)

        right_layout.addWidget(self.popular_stocks_group)

        # 将左右面板添加到水平布局
        tables_layout.addWidget(left_panel, 1)  # 左侧宽度比例为1
        tables_layout.addWidget(right_panel, 1)  # 右侧宽度比例为1

        # 将表格容器添加到主布局
        layout.addWidget(tables_container, 5)  # 占据50%高度

        # ===================== 跟单信息区域 =====================
        follow_group = QGroupBox("跟单信息")
        follow_layout = QVBoxLayout(follow_group)

        # 跟单状态标签
        follow_status_layout = QHBoxLayout()
        self.follow_status_label = QLabel("上次跟单: - | 成功: 0条 | 账户余额: -")
        self.follow_status_label.setStyleSheet("font-weight: bold; color: #333;")
        follow_status_layout.addWidget(self.follow_status_label)
        follow_status_layout.addStretch()

        # 添加刷新按钮
        self.refresh_follow_btn = QPushButton("刷新")
        self.refresh_follow_btn.clicked.connect(self.refresh_follow_trades)
        follow_status_layout.addWidget(self.refresh_follow_btn)

        follow_layout.addLayout(follow_status_layout)

        # 跟单信息表格
        self.follow_table = QTableWidget(0, 9)  # 增加一列显示账户余额
        self.follow_table.setHorizontalHeaderLabels([
            "时间", "高手", "股票代码", "股票名称", "操作", "价格", "数量", "盈亏", "账户余额"
        ])
        self.follow_table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 设置高手名称可点击
        self.follow_table.cellClicked.connect(self.show_master_follow_trades)

        follow_layout.addWidget(self.follow_table)

        layout.addWidget(follow_group, 3)  # 占据30%高度

        # ===================== 系统日志区域 =====================
        self.log_group = QGroupBox("系统日志")
        log_layout = QVBoxLayout(self.log_group)

        self.log_text = QTextEdit()
        self.log_text.setReadOnly(True)
        log_layout.addWidget(self.log_text)

        # 添加日志区域到主布局
        layout.addWidget(self.log_group, 2)  # 占据20%高度

        # 添加选项卡
        self.tabs.addTab(monitor_tab, "交易监控")

        # 设置表格样式
        self.set_table_style()

        # 初始化热门股票统计
        self.refresh_popular_stocks()
        # 初始化跟单信息
        self.refresh_follow_trades()

    def _start_monitoring(self, interval=None):
        """启动监控 - 修复版"""
        # 获取间隔时间
        if interval is None:
            # 关键修复：确保从UI控件获取值
            try:
                interval = self.interval_spin.value()
                logger.debug(f"从微调框获取间隔时间: {interval}秒")
            except Exception as e:
                logger.error(f"获取监控间隔失败: {str(e)}")
                interval = 100  # 默认值
        else:
            try:
                interval = int(interval)
            except (TypeError, ValueError):
                logger.error(f"无效的间隔时间: {interval}, 使用默认值300")
                interval = 100

        # 确保间隔在有效范围内
        interval = max(30, min(600, interval))

        # 记录最终使用的间隔时间
        logger.info(f"最终使用的监控间隔: {interval}秒")

        # 调用监控系统
        try:
            self.system.monitor.start_monitoring(interval)
            logger.info("监控系统启动成功")
        except Exception as e:
            logger.error(f"启动监控系统失败: {str(e)}")
            self.log_text.append(f"启动监控失败: {str(e)}")
            return

        # 更新UI状态
        self.status_label.setText("监控运行中")
        self.start_button.setEnabled(False)
        self.stop_button.setEnabled(True)

        # 输出日志
        self.log_text.append(f"监控已启动，间隔: {interval}秒")
        logger.info(f"监控已启动，间隔: {interval}秒")

    def _stop_monitoring(self):
        """停止监控的实际实现"""
        try:
            self.system.monitor.stop_monitoring()
            logger.info("监控系统停止成功")
        except Exception as e:
            logger.error(f"停止监控系统失败: {str(e)}")
            self.log_text.append(f"停止监控失败: {str(e)}")
            return

        # 更新UI状态
        self.status_label.setText("监控已停止")
        self.start_button.setEnabled(True)
        self.stop_button.setEnabled(False)

        # 输出日志
        self.log_text.append("监控已停止")
        logger.info("监控已停止")
    def set_table_style(self):
        """设置表格样式"""
        # 设置监控高手表格样式
        self.monitor_table.setStyleSheet("""
            QTableWidget {
                background-color: #FFFFFF;
                alternate-background-color: #F0F0F0;
                gridline-color: #D0D0D0;
                font-size: 12px;
            }
            QHeaderView::section {
                background-color: #E0E0E0;
                padding: 4px;
                border: 1px solid #C0C0C0;
                font-weight: bold;
            }
        """)

        # 设置热门股票表格样式
        self.popular_stocks_table.setStyleSheet("""
            QTableWidget {
                background-color: #FFFFFF;
                alternate-background-color: #F0F0F0;
                gridline-color: #D0D0D0;
                font-size: 12px;
            }
            QHeaderView::section {
                background-color: #E0E0E0;
                padding: 4px;
                border: 1px solid #C0C0C0;
                font-weight: bold;
            }
        """)

        # 设置跟单信息表格样式
        self.follow_table.setStyleSheet("""
            QTableWidget {
                background-color: #FFFFFF;
                alternate-background-color: #F0F0F0;
                gridline-color: #D0D0D0;
                font-size: 12px;
            }
            QHeaderView::section {
                background-color: #E0E0E0;
                padding: 4px;
                border: 1px solid #C0C0C0;
                font-weight: bold;
            }
        """)

        # 设置日志区域样式
        self.log_text.setStyleSheet("""
            QTextEdit {
                background-color: #FFFFFF;
                border: 1px solid #C0C0C0;
                font-family: Consolas, Courier New;
                font-size: 11px;
            }
        """)
    def start_monitoring(self, interval):
        """启动监控 - 修复版"""
        # 记录调用参数
        logger.debug(f"调用start_monitoring, interval: {interval}")

        # 获取有效间隔时间
        if interval is None:
            # 尝试从UI控件获取
            if hasattr(self, 'interval_spin') and self.interval_spin is not None:
                try:
                    interval = int(self.interval_spin.value())
                    logger.debug(f"从微调框获取间隔时间: {interval}秒")
                except Exception as e:
                    logger.error(f"获取微调框值失败: {str(e)}")
                    interval = 100
            else:
                logger.warning("监控间隔微调框未初始化，使用默认值300")
                interval = 100
        else:
            # 尝试转换参数
            try:
                interval = int(interval)
                logger.debug(f"使用传入的间隔时间: {interval}秒")
            except (TypeError, ValueError):
                logger.error(f"无效的间隔时间: {interval}, 使用默认值100")
                interval = 100

        # 确保间隔在有效范围内
        interval = max(60, min(600, interval))

        # 记录最终使用的间隔时间
        logger.info(f"最终使用的监控间隔: {interval}秒")

        # 调用监控系统
        try:
            self.system.monitor.start_monitoring(interval)
            logger.info("监控系统启动成功")
        except Exception as e:
            logger.error(f"启动监控系统失败: {str(e)}")
            self.log_text.append(f"启动监控失败: {str(e)}")
            return

        # 更新UI状态
        self.status_label.setText("监控运行中")
        self.start_button.setEnabled(False)
        self.stop_button.setEnabled(True)

        # 输出日志 - 修复输出格式
        self.log_text.append(f"监控已启动，间隔: {interval}秒")
        logger.info(f"监控已启动，间隔: {interval}秒")

    def stop_monitoring(self):
        """停止监控"""
        self.system.monitor.stop_monitoring()
        self.status_label.setText("监控已停止")
        self.start_button.setEnabled(True)
        self.stop_button.setEnabled(False)

        # 更新日志
        self.log_text.append("监控已停止")

    def show_master_details(self, row, column):
        """显示高手买卖详情"""
        if column != 2:  # 只响应"买入高手数"列的点击
            return

        # 获取股票代码
        stock_code = self.popular_stocks_table.item(row, 0).text()

        # 从缓存中获取股票数据
        stock_data = self.popular_stocks_cache.get(stock_code)
        if not stock_data:
            return

        # 创建详情对话框
        dialog = QDialog(self)
        dialog.setWindowTitle(f"{stock_code} {stock_data['stock_name']} - 高手买卖详情")
        dialog.setGeometry(100, 100, 600, 400)

        layout = QVBoxLayout(dialog)

        # 创建滚动区域
        scroll_area = QScrollArea()
        scroll_widget = QWidget()
        scroll_layout = QVBoxLayout(scroll_widget)

        # 添加标题
        title_label = QLabel(
            f"股票: {stock_code} {stock_data['stock_name']} | 买入高手数: {stock_data['buyer_count']}")
        title_label.setStyleSheet("font-weight: bold; font-size: 14px;")
        scroll_layout.addWidget(title_label)

        # 添加高手交易详情
        for buyer in stock_data['buyers']:
            # 检查是否是跟踪中的高手
            is_followed = self.system.db_manager.is_master_followed(buyer['master_id'])

            buyer_group = QGroupBox(f"高手: {buyer['master_name']}")
            if is_followed:
                buyer_group.setStyleSheet("background-color: #E6F7FF; border: 1px solid #91D5FF;")

            buyer_layout = QFormLayout(buyer_group)

            # 添加高手类型（Notes字段）
            master_type = self.system.db_manager.get_master_notes(buyer['master_id'])
            type_label = QLabel(master_type if master_type else "未设置")
            buyer_layout.addRow("高手类型:", type_label)

            buyer_layout.addRow("操作:", QLabel(buyer['trade_type']))
            buyer_layout.addRow("价格:", QLabel(f"{buyer['trade_price']:.2f}"))
            buyer_layout.addRow("数量:", QLabel(str(buyer['trade_volume'])))
            buyer_layout.addRow("交易时间:", QLabel(buyer['trade_date']))

            # 如果是跟踪中的高手，添加标记
            if is_followed:
                follow_label = QLabel("(跟踪中)")
                follow_label.setStyleSheet("color: #1890FF; font-weight: bold;")
                buyer_layout.addRow("状态:", follow_label)

            scroll_layout.addWidget(buyer_group)

        scroll_layout.addStretch()

        # 设置滚动区域
        scroll_area.setWidget(scroll_widget)
        scroll_area.setWidgetResizable(True)
        layout.addWidget(scroll_area)

        # 添加关闭按钮
        close_button = QPushButton("关闭")
        close_button.clicked.connect(dialog.accept)
        layout.addWidget(close_button)

        dialog.exec_()

    def refresh_follow_trades(self):
        """刷新跟单信息"""
        try:
            # 从数据库获取跟单记录
            query = """
                            SELECT 
                                t.TradeDate AS time,
                                m.MasterName AS master,
                                t.StockCode AS stockcode,
                                t.StockName AS stockname,
                                t.TradeType AS operation,
                                st.SimPrice AS price,
                                st.SimVolume AS volume,
                                st.ProfitLoss AS profit,
                                st.Profitsyje AS balance
                            FROM SimulatedTrades st
                            JOIN Trades t ON st.TradeID = t.TradeID
                            JOIN Masters m ON t.MasterID = m.MasterID
                            ORDER BY st.SimDate DESC
                            LIMIT 100
                        """
            trades = self.system.db_manager.execute_query(query, fetch=True)

            # 获取最新账户余额
            latest_balance = self.system.db_manager.get_latest_balance()

            # 更新状态标签
            update_time = datetime.now().strftime("%H:%M:%S")
            self.follow_status_label.setText(
                f"上次跟单: {update_time} | 成功: {len(trades)}条 | 账户余额: {latest_balance:.2f}")

            # 清空表格
            self.follow_table.setRowCount(0)

            # 填充表格
            for i, trade in enumerate(trades):
                self.follow_table.insertRow(i)
                self.follow_table.setItem(i, 0, QTableWidgetItem(trade['time']))
                self.follow_table.setItem(i, 1, QTableWidgetItem(trade['master']))
                self.follow_table.setItem(i, 2, QTableWidgetItem(trade['stockcode']))
                self.follow_table.setItem(i, 3, QTableWidgetItem(trade['stockname']))
                self.follow_table.setItem(i, 4, QTableWidgetItem(trade['operation']))
                self.follow_table.setItem(i, 5, QTableWidgetItem(str(trade['price'])))
                self.follow_table.setItem(i, 6, QTableWidgetItem(str(trade['volume'])))

                # 设置盈亏颜色
                profit_item = QTableWidgetItem(str(trade['profit']))
                if trade['profit'] > 0:
                    profit_item.setForeground(QColor(0, 128, 0))  # 绿色
                elif trade['profit'] < 0:
                    profit_item.setForeground(QColor(255, 0, 0))  # 红色
                self.follow_table.setItem(i, 7, profit_item)

                # 账户余额
                balance_item = QTableWidgetItem(str(trade['balance']))
                self.follow_table.setItem(i, 8, balance_item)

                # 设置行高
                self.follow_table.setRowHeight(i, 15)
        except Exception as e:
            logger.error(f"刷新跟单信息失败: {str(e)}")

    def show_master_trades(self, row, column):
        """显示高手所有买卖记录"""
        if column != 1:  # 只响应"高手"列的点击
            return

        # 获取高手名称
        master_name = self.monitor_table.item(row, 1).text()

        # 获取高手所有交易记录
        trades = self.system.db_manager.get_trades_by_master_name(master_name)

        # 创建详情对话框
        dialog = QDialog(self)
        dialog.setWindowTitle(f"{master_name} - 所有交易记录")
        dialog.setGeometry(100, 100, 800, 600)

        layout = QVBoxLayout(dialog)

        # 创建表格
        table = QTableWidget(len(trades), 7)
        table.setHorizontalHeaderLabels([
            "时间", "股票代码", "股票名称", "操作", "价格", "数量", "状态"
        ])
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 填充表格
        for i, trade in enumerate(trades):
            table.setItem(i, 0, QTableWidgetItem(trade['TradeDate']))
            table.setItem(i, 1, QTableWidgetItem(trade['StockCode']))
            table.setItem(i, 2, QTableWidgetItem(trade['StockName']))
            table.setItem(i, 3, QTableWidgetItem(trade['TradeType']))
            table.setItem(i, 4, QTableWidgetItem(str(trade['TradePrice'])))
            table.setItem(i, 5, QTableWidgetItem(str(trade['TradeVolume'])))

            # 状态
            status = "未跟单"
            if trade.get('SimResult'):
                status = trade['SimResult']
            table.setItem(i, 6, QTableWidgetItem(status))

        layout.addWidget(table)

        # 添加关闭按钮
        close_button = QPushButton("关闭")
        close_button.clicked.connect(dialog.accept)
        layout.addWidget(close_button)

        dialog.exec_()

    def show_master_follow_trades(self, row, column):
        """显示高手所有跟单记录"""
        if column != 1:  # 只响应"高手"列的点击
            return

        # 获取高手名称
        master_name = self.follow_table.item(row, 1).text()

        # 获取高手所有跟单记录
        query = """
                        SELECT 
                            t.TradeDate AS time,
                            t.StockCode AS stockcode,
                            t.StockName AS stockname,
                            t.TradeType AS operation,
                            st.SimPrice AS price,
                            st.SimVolume AS volume,
                            st.ProfitLoss AS profit,
                            st.Profitsyje AS balance
                        FROM SimulatedTrades st
                        JOIN Trades t ON st.TradeID = t.TradeID
                        JOIN Masters m ON t.MasterID = m.MasterID
                        WHERE m.MasterName = ?
                        ORDER BY st.SimDate DESC
                    """
        trades = self.system.db_manager.execute_query(query, (master_name,), fetch=True)

        # 创建详情对话框
        dialog = QDialog(self)
        dialog.setWindowTitle(f"{master_name} - 所有跟单记录")
        dialog.setGeometry(100, 100, 800, 600)

        layout = QVBoxLayout(dialog)

        # 创建表格
        table = QTableWidget(len(trades), 8)
        table.setHorizontalHeaderLabels([
            "时间", "股票代码", "股票名称", "操作", "价格", "数量", "盈亏", "账户余额"
        ])
        table.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)

        # 填充表格
        for i, trade in enumerate(trades):
            table.setItem(i, 0, QTableWidgetItem(trade['time']))
            table.setItem(i, 1, QTableWidgetItem(trade['stockcode']))
            table.setItem(i, 2, QTableWidgetItem(trade['stockname']))
            table.setItem(i, 3, QTableWidgetItem(trade['operation']))
            table.setItem(i, 4, QTableWidgetItem(str(trade['price'])))
            table.setItem(i, 5, QTableWidgetItem(str(trade['volume'])))

            # 盈亏
            profit_item = QTableWidgetItem(str(trade['profit']))
            if trade['profit'] > 0:
                profit_item.setForeground(QColor(0, 128, 0))  # 绿色
            elif trade['profit'] < 0:
                profit_item.setForeground(QColor(255, 0, 0))  # 红色
            table.setItem(i, 6, profit_item)

            # 账户余额
            table.setItem(i, 7, QTableWidgetItem(str(trade['balance'])))

        layout.addWidget(table)

        # 添加关闭按钮
        close_button = QPushButton("关闭")
        close_button.clicked.connect(dialog.accept)
        layout.addWidget(close_button)

        dialog.exec_()

    def check_auto_start(self):
        """检查是否需要自动启动监控"""
        try:
            # 获取当前时间
            now = datetime.now()

            # 检查是否是交易日（周一至周五）
            if now.weekday() >= 5:  # 5=周六, 6=周日
                return

            # 检查时间是否是9:15
            if now.hour == 9 and now.minute == 15:
                # 检查监控是否已经启动
                if not self.system.monitor.monitoring_active:
                    # 启动监控
                    self.start_monitoring()
                    self.log_text.append("每日9:15自动启动监控")
        except Exception as e:
            logger.error(f"自动启动监控检查失败: {str(e)}")

    def toggle_sound(self):
        """切换声音开关"""
        self.sound_enabled = self.sound_toggle.currentData()
        status = "开启" if self.sound_enabled else "关闭"
        self.log_text.append(f"声音提醒已{status}")
    def refresh_popular_stocks(self):
        """刷新热门股票统计"""
        try:
            # 获取当天热门股票数据
            popular_stocks = self.system.db_manager.get_popular_stocks()
            self.popular_stocks_cache = popular_stocks  # 缓存数据

            # 更新状态标签
            update_time = datetime.now().strftime("%H:%M:%S")
            stock_count = len(popular_stocks)
            self.popular_status_label.setText(f"上次更新: {update_time} | 热门股票数: {stock_count}")

            # 清空表格
            self.popular_stocks_table.setRowCount(0)

            # 如果没有数据，显示提示信息
            if not popular_stocks:
                self.popular_stocks_table.setRowCount(1)
                self.popular_stocks_table.setItem(0, 0, QTableWidgetItem("暂无热门股票"))
                return

            # 填充表格
            row = 0
            for stock_code, stock_data in popular_stocks.items():
                self.popular_stocks_table.insertRow(row)
                self.popular_stocks_table.setItem(row, 0, QTableWidgetItem(stock_code))
                self.popular_stocks_table.setItem(row, 1, QTableWidgetItem(stock_data['stock_name']))

                # 买入高手数单元格
                buyer_count_item = QTableWidgetItem(str(stock_data['buyer_count']))
                buyer_count_item.setFlags(buyer_count_item.flags() | Qt.ItemIsUserCheckable)
                buyer_count_item.setData(Qt.UserRole, stock_code)  # 存储股票代码
                self.popular_stocks_table.setItem(row, 2, buyer_count_item)

                # 设置行高
                self.popular_stocks_table.setRowHeight(row, 15)
                row += 1
        except Exception as e:
            logger.error(f"刷新热门股票统计失败: {str(e)}")


    @pyqtSlot(dict)
    def handle_new_trade(self, trade):
        """处理新交易记录"""
        try:
            # 添加到表格
            self.add_to_trade_table(trade)

            # 播放声音提醒
            if self.sound_enabled:
                winsound.Beep(1000, 500)

            # 更新日志
            self.log_text.append(f"新交易: {trade['master']} {trade['operation']} {trade['stock_name']}")

            # 刷新热门股票统计
            self.refresh_popular_stocks()
        except Exception as e:
            logger.error(f"处理新交易失败: {str(e)}")

    def add_to_trade_table(self, trade):
        """添加交易记录到表格"""
        row_position = self.monitor_table.rowCount()
        self.monitor_table.insertRow(row_position)

        # 添加交易数据
        self.monitor_table.setItem(row_position, 0, QTableWidgetItem(trade['time']))
        self.monitor_table.setItem(row_position, 1, QTableWidgetItem(trade['master']))
        self.monitor_table.setItem(row_position, 2, QTableWidgetItem(trade['stockcode']))
        self.monitor_table.setItem(row_position, 3, QTableWidgetItem(trade['stockname']))
        self.monitor_table.setItem(row_position, 4, QTableWidgetItem(trade['operation']))
        self.monitor_table.setItem(row_position, 5, QTableWidgetItem(str(trade['price'])))
        self.monitor_table.setItem(row_position, 6, QTableWidgetItem(str(trade['volume'])))
        self.monitor_table.setItem(row_position, 7, QTableWidgetItem(trade['status']))

        # 设置行高
        self.monitor_table.setRowHeight(row_position, 15)

        # 更新状态标签
        update_time = datetime.now().strftime("%H:%M:%S")
        self.monitor_status_label.setText(f"上次更新: {update_time} | 新增: {row_position + 1}条")

    @pyqtSlot(str)
    def handle_status_update(self, status):
        """处理状态更新"""
        self.status_label.setText(status)

    @pyqtSlot(str, str)
    def handle_log_message(self, message, level):
        """处理日志消息"""
        # 一律使用黑色文字
        self.log_text.append(f'<span style="color:#000000">{message}</span>')

    def refresh_monitor_trades(self):
        """刷新监控交易记录"""
        try:
            # 从数据库获取最新交易记录（仅跟踪高手）
            query = """
                            SELECT 
                                t.TradeDate AS time,
                                m.MasterName AS master,
                                t.StockCode AS stockcode,
                                t.StockName AS stockname,
                                t.TradeType AS operation,
                                t.TradePrice AS price,
                                t.TradeVolume AS volume,
                                st.SimResult AS status
                            FROM Trades t
                            JOIN Masters m ON t.MasterID = m.MasterID
                            LEFT JOIN SimulatedTrades st ON t.TradeID = st.TradeID
                            WHERE m.FolloweStatus = 1  -- 只显示跟踪高手
                            ORDER BY t.TradeDate DESC  -- 按时间从晚到早排序
                            LIMIT 100
                        """
            trades = self.system.db_manager.execute_query(query, fetch=True)

            # 清空表格
            self.monitor_table.setRowCount(0)

            # 填充表格
            for i, trade in enumerate(trades):
                self.monitor_table.insertRow(i)
                self.monitor_table.setItem(i, 0, QTableWidgetItem(trade['time']))
                self.monitor_table.setItem(i, 1, QTableWidgetItem(trade['master']))
                self.monitor_table.setItem(i, 2, QTableWidgetItem(trade['stockcode']))
                self.monitor_table.setItem(i, 3, QTableWidgetItem(trade['stockname']))
                self.monitor_table.setItem(i, 4, QTableWidgetItem(trade['operation']))
                self.monitor_table.setItem(i, 5, QTableWidgetItem(str(trade['price'])))
                self.monitor_table.setItem(i, 6, QTableWidgetItem(str(trade['volume'])))
                self.monitor_table.setItem(i, 7, QTableWidgetItem(trade['status'] if trade['status'] else "未跟单"))

                # 设置行高
                self.monitor_table.setRowHeight(i, 15)

            # 更新状态标签
            update_time = datetime.now().strftime("%H:%M:%S")
            self.monitor_status_label.setText(f"上次更新: {update_time} | 显示: {len(trades)}条")
        except Exception as e:
            logger.error(f"刷新监控交易记录失败: {str(e)}")

    def closeEvent(self, event):
        """关闭窗口事件"""
        # 停止监控
        if self.system.monitor.monitoring_active:
            self.system.monitor.stop_monitoring()

        # 关闭数据库连接
        self.system.db_manager.close()

        event.accept()